
import MenuToggle from '../components/MenuToggle';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import React, { useState } from 'react';
import { DialogContent, DialogTitle, DialogFooter, Dialog, DialogHeader, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { Pause, MoreVertical, GitBranch, CheckCircle, Edit, Users, Clock, Eye, Trash2, Play, Filter, Search, X, AlertCircle, Plus } from 'lucide-react';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
const WorkflowList = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedWorkflows, setSelectedWorkflows] = useState([]);
  const [filterStatus, setFilterStatus] = useState('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);

  // 模拟工作流数据
  const [workflows, setWorkflows] = useState([
    {
      id: 1,
      name: '用户注册审批流程',
      description: '新用户注册后的审批和激活流程',
      status: 'active',
      category: '用户管理',
      version: 'v1.2',
      createTime: '2024-01-15',
      updateTime: '2024-01-20',
      creator: '张三',
      nodeCount: 5,
      instanceCount: 23,
      successRate: 95.6
    },
    {
      id: 2,
      name: '文件上传处理流程',
      description: '文件上传后的病毒扫描、格式转换和存储流程',
      status: 'active',
      category: '文件管理',
      version: 'v2.0',
      createTime: '2024-01-10',
      updateTime: '2024-01-18',
      creator: '李四',
      nodeCount: 8,
      instanceCount: 156,
      successRate: 98.2
    },
    {
      id: 3,
      name: '订单处理工作流',
      description: '从订单创建到完成的完整处理流程',
      status: 'draft',
      category: '业务流程',
      version: 'v1.0',
      createTime: '2024-01-08',
      updateTime: '2024-01-16',
      creator: '王五',
      nodeCount: 12,
      instanceCount: 0,
      successRate: 0
    },
    {
      id: 4,
      name: '数据备份流程',
      description: '定期数据备份和验证流程',
      status: 'inactive',
      category: '系统维护',
      version: 'v1.1',
      createTime: '2024-01-05',
      updateTime: '2024-01-14',
      creator: '赵六',
      nodeCount: 6,
      instanceCount: 45,
      successRate: 89.3
    },
    {
      id: 5,
      name: '异常处理流程',
      description: '系统异常检测和自动处理流程',
      status: 'error',
      category: '系统监控',
      version: 'v1.3',
      createTime: '2024-01-12',
      updateTime: '2024-01-19',
      creator: '钱七',
      nodeCount: 7,
      instanceCount: 12,
      successRate: 67.8
    }
  ]);

  const [newWorkflow, setNewWorkflow] = useState({
    name: '',
    description: '',
    category: '',
    status: 'draft'
  });

  // 过滤工作流数据
  const filteredWorkflows = workflows.filter(workflow => {
    const matchesSearch = workflow.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         workflow.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         workflow.category.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || workflow.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const handleWorkflowSelect = (workflowId) => {
    setSelectedWorkflows(prev => 
      prev.includes(workflowId) 
        ? prev.filter(id => id !== workflowId)
        : [...prev, workflowId]
    );
  };

  const handleSelectAll = () => {
    if (selectedWorkflows.length === filteredWorkflows.length) {
      setSelectedWorkflows([]);
    } else {
      setSelectedWorkflows(filteredWorkflows.map(workflow => workflow.id));
    }
  };

  const handleCreateWorkflow = () => {
    const id = Math.max(...workflows.map(w => w.id)) + 1;
    const currentTime = new Date().toISOString().split('T')[0];
    
    setWorkflows(prev => [...prev, {
      ...newWorkflow,
      id,
      version: 'v1.0',
      createTime: currentTime,
      updateTime: currentTime,
      creator: '当前用户',
      nodeCount: 0,
      instanceCount: 0,
      successRate: 0
    }]);
    
    setNewWorkflow({
      name: '',
      description: '',
      category: '',
      status: 'draft'
    });
    setShowCreateDialog(false);
  };

  const handleDeleteWorkflow = (workflowId) => {
    setWorkflows(prev => prev.filter(workflow => workflow.id !== workflowId));
    setSelectedWorkflows(prev => prev.filter(id => id !== workflowId));
  };

  const handleToggleStatus = (workflowId) => {
    setWorkflows(prev => prev.map(workflow => 
      workflow.id === workflowId ? {
        ...workflow,
        status: workflow.status === 'active' ? 'inactive' : 'active',
        updateTime: new Date().toISOString().split('T')[0]
      } : workflow
    ));
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      active: { color: 'bg-green-100 text-green-800', text: '运行中' },
      inactive: { color: 'bg-gray-100 text-gray-800', text: '已停用' },
      draft: { color: 'bg-blue-100 text-blue-800', text: '草稿' },
      error: { color: 'bg-red-100 text-red-800', text: '错误' }
    };
    
    const config = statusConfig[status] || statusConfig.draft;
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const getCategoryBadge = (category) => {
    const categoryConfig = {
      '用户管理': { color: 'bg-purple-100 text-purple-800' },
      '文件管理': { color: 'bg-blue-100 text-blue-800' },
      '业务流程': { color: 'bg-orange-100 text-orange-800' },
      '系统维护': { color: 'bg-cyan-100 text-cyan-800' },
      '系统监控': { color: 'bg-pink-100 text-pink-800' }
    };
    
    const config = categoryConfig[category] || categoryConfig['业务流程'];
    return (
      <Badge variant="secondary" className={`${config.color} hover:${config.color}`}>
        {category}
      </Badge>
    );
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'active':
        return <Play className="w-5 h-5 text-green-600" />;
      case 'inactive':
        return <Pause className="w-5 h-5 text-gray-600" />;
      case 'error':
        return <AlertCircle className="w-5 h-5 text-red-600" />;
      default:
        return <X className="w-5 h-5 text-blue-600" />;
    }
  };

  const activeCount = workflows.filter(w => w.status === 'active').length;
  const draftCount = workflows.filter(w => w.status === 'draft').length;
  const errorCount = workflows.filter(w => w.status === 'error').length;
  const totalInstances = workflows.reduce((sum, workflow) => sum + workflow.instanceCount, 0);

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <GitBranch className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    流程管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理和监控工作流程
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索工作流..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">运行中</SelectItem>
                  <SelectItem value="inactive">已停用</SelectItem>
                  <SelectItem value="draft">草稿</SelectItem>
                  <SelectItem value="error">错误</SelectItem>
                </SelectContent>
              </Select>

              <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
                <DialogTrigger asChild>
                  <Button className="bg-primary hover:bg-primary-600">
                    <Plus className="w-4 h-4 mr-2" />
                    新建工作流
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-lg">
                  <DialogHeader>
                    <DialogTitle>新建工作流</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="name">工作流名称</Label>
                      <Input
                        id="name"
                        value={newWorkflow.name}
                        onChange={(e) => setNewWorkflow(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="请输入工作流名称"
                      />
                    </div>
                    <div>
                      <Label htmlFor="description">工作流描述</Label>
                      <Textarea
                        id="description"
                        value={newWorkflow.description}
                        onChange={(e) => setNewWorkflow(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="请输入工作流描述"
                        rows={3}
                      />
                    </div>
                    <div>
                      <Label htmlFor="category">分类</Label>
                      <Select value={newWorkflow.category} onValueChange={(value) => setNewWorkflow(prev => ({ ...prev, category: value }))}>
                        <SelectTrigger>
                          <SelectValue placeholder="请选择分类" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="用户管理">用户管理</SelectItem>
                          <SelectItem value="文件管理">文件管理</SelectItem>
                          <SelectItem value="业务流程">业务流程</SelectItem>
                          <SelectItem value="系统维护">系统维护</SelectItem>
                          <SelectItem value="系统监控">系统监控</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowCreateDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={handleCreateWorkflow}>
                      创建工作流
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总工作流</p>
                  <p className="text-2xl font-bold text-material-grey-900">{workflows.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <GitBranch className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">运行中</p>
                  <p className="text-2xl font-bold text-green-600">{activeCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Play className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">草稿</p>
                  <p className="text-2xl font-bold text-blue-600">{draftCount}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Edit className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总实例数</p>
                  <p className="text-2xl font-bold text-purple-600">{totalInstances}</p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Users className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 工作流列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <input
                      type="checkbox"
                      checked={selectedWorkflows.length === filteredWorkflows.length && filteredWorkflows.length > 0}
                      onChange={handleSelectAll}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </TableHead>
                  <TableHead>工作流信息</TableHead>
                  <TableHead>分类</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>节点数</TableHead>
                  <TableHead>实例数</TableHead>
                  <TableHead>成功率</TableHead>
                  <TableHead>创建者</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredWorkflows.map((workflow) => (
                  <TableRow key={workflow.id}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedWorkflows.includes(workflow.id)}
                        onChange={() => handleWorkflowSelect(workflow.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center space-x-3">
                          {getStatusIcon(workflow.status)}
                          <div>
                            <p className="font-medium text-material-grey-900">{workflow.name}</p>
                            <p className="text-sm text-material-grey-500">版本: {workflow.version}</p>
                          </div>
                        </div>
                        <p className="text-xs text-material-grey-600 ml-8">{workflow.description}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      {getCategoryBadge(workflow.category)}
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(workflow.status)}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{workflow.nodeCount} 个</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{workflow.instanceCount}</span>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <span className={`text-sm font-medium ${
                          workflow.successRate >= 95 ? 'text-green-600' :
                          workflow.successRate >= 80 ? 'text-yellow-600' : 'text-red-600'
                        }`}>
                          {workflow.successRate}%
                        </span>
                        {workflow.successRate >= 95 && <CheckCircle className="w-4 h-4 text-green-600" />}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{workflow.creator}</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Edit className="w-4 h-4 mr-2" />
                            编辑设计
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleToggleStatus(workflow.id)}>
                            {workflow.status === 'active' ? (
                              <>
                                <Pause className="w-4 h-4 mr-2" />
                                停用
                              </>
                            ) : (
                              <>
                                <Play className="w-4 h-4 mr-2" />
                                启用
                              </>
                            )}
                          </DropdownMenuItem>
                          <DropdownMenuItem 
                            onClick={() => handleDeleteWorkflow(workflow.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredWorkflows.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <GitBranch className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的工作流' : '暂无工作流'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '点击上方按钮开始创建工作流'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default WorkflowList;
